All files / src/app/api/sort-results/[id]/supersede route.ts

93.33% Statements 14/15
83.33% Branches 5/6
100% Functions 1/1
92.85% Lines 13/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34                5x           9x 9x 9x 8x 8x 8x   5x 5x 9x 3x     3x     3x      
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { requireAuth } from "@/lib/auth";
import { SortResultService } from "@/server/services/SortResultService";
import { errorResponse } from "@/server/api/http-errors";
import { getDb } from "@/lib/db";
import { requireApiResultAccess } from "@/server/dal/collection-access";
 
const SupersedeBody = z.object({ discardPins: z.literal(true).optional() }).strict();
 
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const user = await requireAuth();
    const db = getDb();
    const access = await requireApiResultAccess(db, id, user.id);
    if (access instanceof NextResponse) return access;
    // Body is optional: no body = "don't discard hand placements". Invalid JSON → 400 via errorResponse.
    const text = await request.text();
    const { discardPins } = SupersedeBody.parse(text ? JSON.parse(text) : {});
    const result = await SortResultService.fromDb(db).supersedeResult(id, { discardPins });
    Iif (!result) {
      return NextResponse.json({ error: "Not found" }, { status: 404 });
    }
    return NextResponse.json(result, { status: 201 });
  } catch (error) {
    // errorResponse maps SupersedeStateError / RevisionDiscardsPinsError → 409, ZodError/SyntaxError → 400, Unauthorized → 401.
    return errorResponse(error);
  }
}